import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormArray, FormBuilder, Validators } from '@angular/forms';
import { mobileValidator, equalValidator } from '../validator/validators';

@Component({
  selector: 'app-reactive-form',
  templateUrl: './reactive-form.component.html',
  styleUrls: ['./reactive-form.component.css']
})
export class ReactiveFormComponent implements OnInit {
  private formModel: FormGroup;
  constructor(public fb: FormBuilder) { }
  
  ngOnInit() {
    //this.formModel = new FormGroup({
    //  userName: new FormControl(),
    //  mobile: new FormControl(),
    //  date: new FormControl(),
    //  emails: new FormArray([
    //    new FormControl("11.com"),
    //    new FormControl("22.com")
    //  ]),
    //  pwdGroup: new FormGroup({
    //    pwd: new FormControl(),
    //    pwdConfirm:new FormControl()
    //  })
    //});
    this.formModel = this.fb.group({
      userName: [, [Validators.required, Validators.minLength(6)]],
      mobile: [, mobileValidator],
      date: [],
      emails: this.fb.array([
        ["11.com"],
        ["22.com"]
      ]),
      pwdGroup: this.fb.group({
        pwd: [, [Validators.required, Validators.minLength(6)]],
        pwdConfirm: []
      }, {validator: equalValidator })
    });
    console.log(this.formModel.controls);
    console.log(this.formModel.get(['pwdGroup', 'pwd']).untouched);
    console.log(this.formModel.get('pwdGroup').get('pwd').untouched);
  }
  onSubmit(form) {
    if (this.formModel.valid) {
      console.log(form.value);
    }
  }
  addEmail(e) {
    let arr = this.formModel.get('emails') as FormArray;
    arr.push(new FormControl());
  }
}
